package com.xiaozhengkeji.springboot.speed.services.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.xiaozhengkeji.springboot.speed.dao.PermissionDao;
import com.xiaozhengkeji.springboot.speed.dao.RoleDao;
import com.xiaozhengkeji.springboot.speed.dao.RolepermissionDao;
import com.xiaozhengkeji.springboot.speed.dao.UserDao;
import com.xiaozhengkeji.springboot.speed.pojo.PermissionPoJo;
import com.xiaozhengkeji.springboot.speed.pojo.RolePoJo;
import com.xiaozhengkeji.springboot.speed.pojo.UserPoJo;
import com.xiaozhengkeji.springboot.speed.services.RedisService;
import com.xiaozhengkeji.springboot.speed.services.UserService;
import com.xiaozhengkeji.springboot.speed.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@SuppressWarnings("ALL")
public class UserServiceImp implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolepermissionDao rolepermissionDao;
    @Autowired
    private RedisService redisService;

    @Override
    public UserPoJo getUser(String username) {
        QueryWrapper<UserPoJo> queryWrapperUser = new QueryWrapper<UserPoJo>();
        queryWrapperUser.eq("username", username);
        UserPoJo userPoJo = userDao.selectOne(queryWrapperUser);
        if (userPoJo == null) {
            return null;
        }
        QueryWrapper<RolePoJo> queryWrapperRole = new QueryWrapper<RolePoJo>();
        queryWrapperRole.eq("rid", userPoJo.getRid());
        userPoJo.setRole(roleDao.selectOne(queryWrapperRole));
        QueryWrapper<PermissionPoJo> queryWrapperpermission = new QueryWrapper<PermissionPoJo>();
        queryWrapperpermission.eq("rid", userPoJo.getRid());
        userPoJo.setPermissions(permissionDao.selectList(queryWrapperpermission));
        return userPoJo;
    }

    @Override
    public Boolean regUser(UserPoJo userPoJo) {
        if (userDao.insert(userPoJo) < 1) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean isToken(String token) {
        String username = JWTUtil.getUsername(token);
        String otoken = (String) redisService.get(username + "_token");
        if (otoken.equalsIgnoreCase(token)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void upToken(String token) {
        String username = JWTUtil.getUsername(token);
        redisService.set(username + "_token", token);
    }

    @Override
    public void outToken(String userName) {
        redisService.set(userName + "_token", "离线");
    }
}
